<?php
class DataBaseService{
	
	private $_resultarray = array();
	private $_csvdata;
	private $_model;
	private $_group;
	private $_sql = 't.*';
	private $_method = 'getAll';
	private $_where;
	private $_order;
	private $_join;
	private $_selectdata;
	private $_selectkey;
	private $_selectval;
	private $_limit;
	protected $_log;
	
	protected function log(){
		return $this->_log;
	}
	
	public function setModel($model){
		$this->_model = $model;
		return $this;
	}
	
	public function setSql($sql){
		$this->_sql = $sql;
		return $this;
	}
	
	public function setGroup($group){
		$this->_group = $group;
		return $this;
	}
	
	public function setMethod($method){
		$this->_method = $method;
		return $this;
	}
	
	public function setWhere($where){
		$this->_where = $where;
		return $this;
	}
	
	public function setOrder($order){
		$this->_order = $order;
		return $this;
	}
	
	public function setJoin($join){
		$this->_join = $join;
		return $this;
	}
	
	public function setLimit($limit){
		$this->_limit = $limit;
		return $this;
	}
	
	public function setSelectData($selectdata){
		$this->_selectdata = $selectdata;
		return $this;
	}
	
	public function setSelectKey($selectkey){
		$this->_selectkey = $selectkey;
		return $this;
	}
	
	public function setSelectVal($selectval){
		$this->_selectval = $selectval;
		return $this;
	}
	
	public function resultToArray($model){
		if(!empty($model)){
			$resultarray = array();
			foreach($model as $key => $val){
				$resultarray[$key] = $val;
			}
			$this->_resultarray = $resultarray;
		}
		return $this;
	}
	
	public function getRow(){
		return array_shift($this->_resultarray);
	}
	
	public function getAll(){
		return $this->_resultarray;
	}
	
	public function initialData(){
		$dbCommand = Yii::app()->db->createCommand()
		->select($this->_sql)
		->from($this->_model->tableName().' t');
		$criteria = $this->_model->getSearchCondition();
		if(!empty($this->_where)){
			$dbCommand->where = $this->_where;
		}
		
		if(!empty($this->_order)){
			$dbCommand->order = $this->_order;
		}
		
		if(!empty($this->_join)){
			$dbCommand->join = $this->_join;
		}else{
			$dbCommand->join = $criteria->join;
		}
		
		if(!empty($this->_group)){
			$dbCommand->group = $this->_group;
		}
		
		if(!empty($this->_limit)){
			$dbCommand->limit = $this->_limit;
		}
		
		if(!empty($criteria->condition)) {
			$dbCommand = $dbCommand->where($criteria->condition, $criteria->params);
		}
		$odata = $dbCommand->query();
		$method = $this->_method;
		$this->_csvdata = $this->resultToArray($odata)->$method();
		return $this;
	}
	
	public function getData(){
		return $this->_csvdata;
	}
	
	public function unInitial(){
		$this->_group = '';
		$this->_order = '';
		$this->_where = '';
		$this->_sql = 't.*';
		$this->_method='getAll';
	}
	
	public function toArraySelect(){
		foreach ($this->_selectdata as $data){
			$selecarray[$data[$this->_selectkey]] = $data[$this->_selectval];
		}
		return $selecarray;
	}
	
	
}